const multer = require('@koa/multer')
const COS = require('cos-nodejs-sdk-v5');
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
    SecretId: process.env.QQ_SECRETID, // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
    SecretKey: process.env.QQ_SECRETKEY, 
    FileParallelLimit:6,
    ChunkParallelLimit:6,
    Protocol:'https',
    UseAccelerate:true
});
// 上传图片到服务器端
const storage = multer.diskStorage({
    filename:(req,file,cb) => {
        let fileFormat = (file.originalname).split('.')
        let newCode = `${new Date().getTime()}.${fileFormat[fileFormat.length-1]}`
        cb(null,newCode)
    }
})

const upload = multer({storage})

// 上传到腾讯云
const cosUpdate = (value) => {
    return new Promise((resolve,reject) => {
        
        const resFile = []
        const files = value.map(item => {
           return {
            Bucket:process.env.QQ_BUCKET,
            Region:process.env.QQ_REGION,
            Key:`${process.env.QQ_FOLDER}${item.filename}`,
            FilePath:item.path
           }
        })
        cos.uploadFiles({files})
        .then(res=>{
            res.files.forEach(item=>resFile.push(`https://${item.data.Location}`))
            resolve(resFile)
        })
        .catch(err=>{
            reject(err)
        })
    })

}


module.exports = {
    upload,
    cosUpdate
}